package thread;

import java.util.Random;

/**
 * Creared with IntelliJ IDEA.
 * Description:
 * User:yxd
 * Date:2022-03-21
 * Time:17:22
 */
public class Demo10 {
    public static long count = 0;
    public static void main(String[] args) {
        Random random = new Random();
        int[] nums = new int[1000_0000];
        for(int i = 0;i < nums.length;i ++){
            nums[i] = random.nextInt(100) + 1;
        }
        long beg = System.currentTimeMillis();
        Thread t1 = new Thread(()->{
            long s1 = 0;
            for(int i = 0;i < nums.length;i += 2){
                s1 += nums[i];//如果相加的数过于少,创建线程也是会花费时间的,多任务时效率会更好
            }
            count += s1;
        });
        t1.start();
        Thread t2 = new Thread(()->{

            long s2 = 0;
            for(int i = 1;i < nums.length;i += 2){
                s2 += nums[i];
            }

            count += s2;


        });
        t2.start();
        try {
            t1.join();
            t2.join();//等待两个线程都完成了在计算时间才是此线程的共用时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("相加时间:" + (end - beg) + "ms");
        System.out.println("总和:" + count);
    }
}
